/**
 * Copyright (C) 2013 The yydorid-framework project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.yangying.androidframework.util;

import java.io.IOException;

import net.yangying.androidframework.core.exception.YYDroidException;
import net.yangying.androidframework.core.exception.YYDroidParseException;
import net.yangying.androidframework.core.http.parser.json.Parser;
import net.yangying.androidframework.core.model.YYDroid;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;




public class JSONUtils {
    
	private static final String TAG = JSONUtils.class.getSimpleName();
    /**
     * Takes a parser, a json string, and returns a wapcn type.
     */
    public static YYDroid consume(Parser<? extends YYDroid> parser, String content)
        throws YYDroidParseException, YYDroidException, IOException {
        
    	if(Constant.DEBUG)
    		Log.d(TAG, "" + content);
        
        try {
            // The v1 API returns the response raw with no wrapper. Depending on the
            // type of API call, the content might be a JSONObject or a JSONArray.
            // Since JSONArray does not derive from JSONObject, we need to check for
            // either of these cases to parse correctly.
            JSONObject json = new JSONObject(content);
//            Iterator<String> it = (Iterator<String>)json.keys();
//            if (it.hasNext()) {
//                String key = (String)it.next();
//                if (key.equals("error")) {
//                    throw new WapcnException(json.getString(key));
//                } else {
//                    Object obj = json.get(key);
//                    if (obj instanceof JSONArray) {
//                        return parser.parse((JSONArray)obj);
//                    } else {
//                    	Log.i(TAG, obj.toString());
//                        return parser.parse((JSONObject)obj);
//                    }
//                }
//            } else {
//                throw new WapcnException("Error parsing JSON response, object had no single child key.");
//            }
            return parser.parse(json);
            
        } catch (JSONException ex) {
            throw new YYDroidException("Error parsing JSON response: " + ex.getMessage());
        }
    }
}